package org.lboot.md.service;

import cn.hutool.core.io.IoUtil;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.lboot.md.domain.MarkdownFile;
import org.lboot.s3.client.S3Client;
import org.lboot.ufs.entity.UfsFile;
import org.lboot.ufs.service.UfsCtl;
import org.lboot.ufs.service.UfsFileService;
import org.lboot.ufs.utils.UfsUtil;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;

@Slf4j
@Service
@AllArgsConstructor
@ConditionalOnClass(UfsCtl.class)
public class DevMarkdownFileService implements MarkdownFileService{
    UfsCtl ufsCtl;

    UfsFileService fileService;

    S3Client s3Client;

    @Resource
    ApplicationContext context;
    @Override
    @SneakyThrows
    public MarkdownFile uploadFile(MultipartFile file) {
        UfsFile ufsFile = UfsUtil.buildFile(file);
        MarkdownFile markdownFile = new MarkdownFile();
        markdownFile.setFileType(ufsFile.getExtName());
        markdownFile.setTitle(ufsFile.getFileName());

        UfsFile uploadRes = ufsCtl.uploadFile(file, ufsFile.getFileType()+"/");
        markdownFile.setKey(uploadRes.getId());
        InputStream stream = file.getInputStream();
        markdownFile.setContent(IoUtil.readUtf8(stream));
        markdownFile.setUrl("/ufs/download/"+uploadRes.getId());
        return markdownFile;
    }

    @Override
    public MarkdownFile getFile(String fileKey) {
        UfsFile ufsFile = fileService.getOneUnwrap(fileKey);
        log.info(ufsFile.toString());
        InputStream stream = ufsCtl.getFileStream(fileKey);
        MarkdownFile markdownFile = new MarkdownFile();
        markdownFile.setFileType(ufsFile.getExtName());
        markdownFile.setTitle(ufsFile.getFileName());
        markdownFile.setKey(ufsFile.getId());
        markdownFile.setContent(IoUtil.readUtf8(stream));
        log.info(markdownFile.getContent());
        markdownFile.setUrl("/ufs/download/"+ufsFile.getId());
        return markdownFile;
    }

    @Override
    @SneakyThrows
    public boolean updateFile(String fileKey, InputStream stream) {
        ufsCtl.updateFile(fileKey,stream);
        return true;
    }

    @Override
    public InputStream getFileStream(String fileKey) {
        return ufsCtl.getFileStream(fileKey);
    }
}
